﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SuperQuiz.Model;
using System.Windows.Threading;

namespace SuperQuiz
{
    public partial class QuestionPage : PhoneApplicationPage
    {
        private UserEvaluation userEvaluation;
        private int CurrentIndex { get; set; }
        DispatcherTimer dt;

        public QuestionPage()
        {
            InitializeComponent();
            this.CurrentIndex = 0;
        }

        private void GoToPrev()
        {


            if (dt != null)
            {
                if (dt.IsEnabled)
                {
                    dt.Stop();
                    dt = null;
                }
            }

            if (CurrentIndex > 0)
            {
                

                if (CheckAnswer() == false)
                {
                    MessageBox.Show("Você errou a questão anterior");
                }
                CurrentIndex--;
                UpdateQuestion();
            }
        }

        private void GoToNext()
        {

            if (dt != null)
            {
                if (dt.IsEnabled)
                {
                    dt.Stop();
                    dt = null;
                }
            }

            if (CurrentIndex < userEvaluation.Questions.Count - 1)
            {
                
                if (CheckAnswer() == false)
                {
                    MessageBox.Show("Você errou a questão anterior");
                }
                CurrentIndex++;
                UpdateQuestion();
            }
            else
            {
                FinishTest();
            }

        }


        private void UpdateQuestion()
        {
            Question currentQuestion = userEvaluation.Questions[CurrentIndex];
            ApplicationTitle.Text = String.Format("{0}/{1}-{2}", CurrentIndex + 1, userEvaluation.Questions.Count, userEvaluation.Name);
            //PageTitle.Text = String.Format("Pergunta {0}/{1}", CurrentIndex + 1, currentTest.Questions.Count);
            QuestionText.Text = currentQuestion.Text;

            //stackPanel1.Children.Clear();

            //currentQuestion.Alternatives = new List<Alternative>();
            //currentQuestion.Alternatives.Add(new Alternative() { Text = "KJljkljL" });


            ListBox.ItemsSource = currentQuestion.MyAlternatives;

            //int i = 1;
            //foreach (String s in currentQuestion.Alternatives)
            //{
            //    RadioButton radioButton = new RadioButton() { Content = s, GroupName = "RadioQuestion", Tag = i  };
            //    if (currentQuestion.UserAnswer == i)
            //    {
            //        radioButton.IsChecked = true;
            //    }
            //    radioButton.Click += new RoutedEventHandler(radioButton_Click);
            //    stackPanel1.Children.Add(radioButton);
            //    i++;
            //}

        }

        void dt_Tick(object sender, EventArgs e)
        {
            if (CurrentIndex < userEvaluation.Questions.Count - 1)
                CurrentIndex++;
            UpdateQuestion();
            dt.Stop();
            dt = null;
        }

        private void FinishTest()
        {
            if (MessageBox.Show("Entregar a prova?", "Finalizar", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                GoToSummaryPage();
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string selectedIndex = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                int index = int.Parse(selectedIndex);

                Test test = (Test)PhoneApplicationService.Current.State["CurrentTest"];
                userEvaluation = MyFactory.GetUserEvaluationFrom(test);
                //currentTest = Controller.Instance.Quiz.Tests[index];
                this.DataContext = userEvaluation;
            }
            UpdateQuestion();
        }


        private void ApplicationBarIconNextButton_Click(object sender, EventArgs e)
        {
            GoToNext();
        }

        private void ApplicationBarIconFinishButton_Click(object sender, EventArgs e)
        {
            FinishTest();
        }


        private void ApplicationBarIconPrevButton_Click(object sender, EventArgs e)
        {
            GoToPrev();
        }

        private void ApplicationBarIconStopButton_Click(object sender, EventArgs e)
        {
            CancelTest();
        }

        private void CancelTest()
        {
            if (MessageBox.Show("Deseja sair?", "Sair", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {

                GoToSummaryPage();
            }
        }

        private void GoToSummaryPage()
        {
            PhoneApplicationService.Current.State["Summary"] = MyFactory.GetSummary(userEvaluation);
            this.NavigationService.Navigate(new Uri("/SummaryPage.xaml", UriKind.Relative));
        }



        void radioButton_Click(object sender, RoutedEventArgs e)
        {

            //Question question = userEvaluation.Questions[CurrentIndex];

            //(ListBox.SelectedItem as Alternative).UserAnswer = 

            //if (CheckAnswer(question)==false)
            //{
            //    MessageBox.Show("Você errou");
            //}
            //else
            //{
            //    if (dt == null)
            //    {

            //        dt = new DispatcherTimer();
            //        dt.Interval = new TimeSpan(0, 0, 0, 0, 750); // 500 Milliseconds
            //        dt.Tick += new EventHandler(dt_Tick);
            //        dt.Start();
            //    }
            //}
        }

        private bool CheckAnswer()
        {


            Question question = userEvaluation.Questions[CurrentIndex];

            foreach (Alternative a in question.MyAlternatives)
            {
                if ((a.UserAnswer) && (a.Value != a.UserAnswer))
                {
                    return false;
                }
            }

            return true;



        }


        private void Gesture_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
            {
                if (e.HorizontalVelocity > 0)
                {
                    GoToPrev();
                }
                else
                {
                    GoToNext();
                }
            }
        }


    }
}